package cn.livingCloud.service.impl.operation;

import cn.livingCloud.context.BeanProvider;
import cn.livingCloud.dto.ArticleReplyDto;
import cn.livingCloud.dto.ArticlesReplyRuleFormDto;
import cn.livingCloud.entity.content.ImageTextReply;
import cn.livingCloud.entity.content.ReplyRule;
import cn.livingCloud.repository.ArticleReplyMapper;
import cn.livingCloud.repository.ImageTextReplyMapper;
import org.apache.commons.lang.StringUtils;

import java.util.List;

/**
 * Created by 唐旭 on 2015/12/26.
 */
public class ArticlesReplyRuleFormDtoUpdater extends ReplyRuleFormDtoUpdater {
    private transient ImageTextReplyMapper imageTextReplyMapper = BeanProvider.getBean(ImageTextReplyMapper.class);
    private transient ArticleReplyMapper articleReplyMapper = BeanProvider.getBean(ArticleReplyMapper.class);

    private ArticlesReplyRuleFormDto formDto;

    public ArticlesReplyRuleFormDtoUpdater(ArticlesReplyRuleFormDto formDto) {
        super(formDto);
        this.formDto = formDto;
    }

    public void update() {
        ReplyRule replyRule = super.updateRule();
        String uuid = formDto.getUuid();
        ArticleReplyUpdater articleReplyUpdater = new ArticleReplyUpdater();
        if (StringUtils.isEmpty(uuid)) {
            createArticlesRule(replyRule, articleReplyUpdater);
        } else {
            updateArticlesRule(replyRule, articleReplyUpdater);
        }
    }

    /**
     * 删除旧数据
     * 添加新数据
     */
    private void updateArticlesRule(ReplyRule replyRule, ArticleReplyUpdater articleReplyUpdater) {
        ImageTextReply imageTextReply = (ImageTextReply) imageTextReplyMapper
                .findContentByRule(replyRule.getUuid());
        //删除旧数据
        deleteOldData(imageTextReply);
        //添加新数据
        saveArticleList(articleReplyUpdater, imageTextReply);
    }

    private void deleteOldData(ImageTextReply imageTextReply) {
        articleReplyMapper.deleteByImageTextReply(imageTextReply.getUuid());
    }

    private void createArticlesRule(ReplyRule replyRule, ArticleReplyUpdater articleReplyUpdater) {
        ImageTextReply imageTextReply = new ImageTextReply(replyRule);
        imageTextReplyMapper.save(imageTextReply);
        saveArticleList(articleReplyUpdater, imageTextReply);
    }

    private void saveArticleList(ArticleReplyUpdater articleReplyUpdater, ImageTextReply imageTextReply) {
        int rank = 0;
        List<ArticleReplyDto> articleList = formDto.getArticles().getArticleList();
        for (ArticleReplyDto articleReplyDto : articleList) {
            rank++;
            articleReplyUpdater.update(articleReplyDto, imageTextReply, rank);
        }
    }
}
